<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="书名" prop="name">
        <el-input v-model="dataForm.name" placeholder="书名"></el-input>
      </el-form-item>

      <el-form-item label="版本" prop="version">
        <el-input v-model="dataForm.version" placeholder="版本"></el-input>
      </el-form-item>
      <el-form-item label="出版商" prop="vendor">
        <el-input v-model="dataForm.vendor" placeholder="出版商"></el-input>
      </el-form-item>
      <el-form-item label="出版时间" prop="publicDate">
        <el-date-picker
          type="date"
          :clearable="false"
          v-model="dataForm.publicDate"
          value-format="yyyy-MM-dd 00:00:00"
          placeholder="出版时间"></el-date-picker>
      </el-form-item>
      <el-form-item label="图书数量" prop="total">
        <el-input-number v-model="dataForm.total" placeholder="图书数量"></el-input-number>
      </el-form-item>
      <el-form-item label="简介" prop="summary">
        <el-input v-model="dataForm.summary"
                  placeholder="简介"
                  type="textarea"
                  :autosize="{ minRows: 3, maxRows: 10}"></el-input>
      </el-form-item>
      <el-form-item label="作者" size="mini" prop="authorIdList">
        <el-transfer
          v-model="dataForm.authorIdList"
          filterable
          :filter-method="filterByName"
          :titles="['作者','选中作者']"
          filter-placeholder="请输入作者名称"
          :data="authorList">
        </el-transfer>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="文件">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
          name="file"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>


      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" v-prevent-db-click @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import '@/utils/preventDbClick'
import _ from 'lodash'

export default {
  data () {
    var filterByName = (query, item) => {
      return item.label.indexOf(query) > -1
    }

    return {
      visible: false,
      uploadUrl: '',
      filterByName,
      authorList: [],
      fileList: [{
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }, {
        name: 'food2.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }],
      fileIds: [],
      dataForm: {
        id: 0,
        name: '',
        version: '',
        vendor: '',
        summary: '',
        status: 1,
        publicDate: '',
        total: '',
        available: 0,
        authorIdList: [],
        createTime: ''
      },
      dataRule: {
        name: [
          {required: true, message: '书名不能为空', trigger: 'blur'}
        ],
        version: [
          {required: true, message: '版本不能为空', trigger: 'blur'}
        ],
        vendor: [
          {required: true, message: '出版商不能为空', trigger: 'blur'}
        ],
        summary: [
          {required: true, message: '简介不能为空', trigger: 'blur'}
        ],
        publicDate: [
          {required: true, message: '出版日期不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    handleRemove (file, fileList) {
      _.remove(fileList, f => {
        return f === file
      })
      _.remove(this.fileList, f => {
        return f.fileId === file.fileId
      })
      console.log(fileList)
      console.log(this.fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleSuccess (response, file, fileList) {
      if (response['code'] !== 0) {
        return
      }
      file.fileId = response.fileId
      this.fileList.push(
        {name: file.name, url: file.url, fileId: file.fileId}
      )
      console.log(response)
      console.log(file)
      console.log(fileList)
    },
    init (id) {
      this.dataForm.id = id || 0
      this.uploadUrl = this.$http.adornUrl(`/sys/file/upload?token=${this.$cookie.get('token')}`)

      this.$http({
        url: this.$http.adornUrl('/sys/author/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.authorList = data && data.code === 0 ? data.list.map((e) => {
          return {key: e.authorId, label: e.username}
        }) : []
        console.log(this.authorList)
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/sys/book/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.book.name
              this.dataForm.version = data.book.version
              this.dataForm.vendor = data.book.vendor
              this.dataForm.summary = data.book.summary
              this.dataForm.status = data.book.status
              this.dataForm.publicDate = data.book.publicDate
              this.dataForm.total = data.book.total
              this.dataForm.available = data.book.available
              this.dataForm.authorIdList = data.book.authorIdList
              this.dataForm.createTime = data.book.createTime
              this.fileList = data.book.fileList.map(e => {
                return {name: e.filename, url: e.url, fileId: e.fileId}
              })
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/book/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'name': this.dataForm.name,
              'version': this.dataForm.version,
              'vendor': this.dataForm.vendor,
              'summary': this.dataForm.summary,
              'status': this.dataForm.status,
              'publicDate': this.dataForm.publicDate,
              'total': this.dataForm.total,
              'available': this.dataForm.available,
              'authorIdList': this.dataForm.authorIdList,
              'fileIdList': this.fileList.map(e => {
                return e.fileId
              }),
              'createTime': this.dataForm.createTime,
              'bookId': this.dataForm.id || undefined
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
